package base.thread_demo.demo21;

import java.util.concurrent.atomic.AtomicStampedReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * AtomicStampedReference带版本号的原子引用,通过版本号监视是否中途被修改
 *
 */
public class Demo02 {
	private static final Logger log = LoggerFactory.getLogger(Demo02.class);

	public static void main(String[] args) {
		test1();
	}

	public static void test1() {
		AtomicStampedReference<String> ref = new AtomicStampedReference<String>("A", 0);//初始引用值A，初始版本号0

		int stamp = ref.getStamp();
		String prev = ref.getReference();

		// other线程对ref进行修改
		other(ref);

		try {
			Thread.sleep(2000);//确保other线程已经顺利执行
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		log.info("{}", stamp);
		log.info("change A -> C is {}", ref.compareAndSet(prev, "C", stamp, stamp+1));
	}

	public static void other(AtomicStampedReference<String> ref) {
		new Thread(()->{
			int stamp = ref.getStamp();
			log.info("{}", stamp);
			log.info("change A -> B is {}", ref.compareAndSet(ref.getReference(), "B", stamp, stamp+1));
		},"t1").start();

		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		new Thread(()->{
			int stamp = ref.getStamp();
			log.info("{}", stamp);
			log.info("change B -> A is {}", ref.compareAndSet(ref.getReference(), "A", stamp, stamp+1));
		},"t2").start();
	}

}
